package com.rzrk.centerlogserver.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.exp.base.action.Message;
import com.exp.base.util.JsonUtils;

public class BaseAction {
	/** "验证结果"参数名称 */
	public static final String ATTRIBUTE_NAME_EXCEPTION = "exception";

	@Resource(name = "validator")
	Validator validator;

	
	@ExceptionHandler({Exception.class})  
    public String exception(Exception e, HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException, IOException {
        e.printStackTrace(); 
        int code = 500;
		if(e instanceof org.apache.shiro.authz.UnauthorizedException){
			code = 403;
		}
		if(com.exp.base.util.WebUtils.isAjax(request)){
			Message message = new Message(false, code,StringUtils.abbreviate(e.getMessage(),64));
			response.setContentType("text/json; charset=UTF-8");
			response.getOutputStream().write(JsonUtils.toString(message).getBytes("utf-8"));
			return null;
		}else{
			response.setStatus(code);
			request.setAttribute(ATTRIBUTE_NAME_EXCEPTION, e.getMessage());
	        return "common/500";  
		}
    }
	
	protected boolean isValid(Object target, List<String> box) {
		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(target);
		if (constraintViolations.isEmpty()) {
			return true;
		} else {
			if(box!=null){
				CollectionUtils.collect(constraintViolations, new Transformer() {
					@Override
					public Object transform(Object arg0) {
						ConstraintViolation<Object> error = (ConstraintViolation<Object>)arg0;
						return error.getPropertyPath()+error.getMessage();
					}
				}, box);
			}
			return false;
		}
	}
	/**
	 * 页面值给后台实体赋值
	 * 
	 * @param request
	 * @param src
	 * @param target
	 * @param prefix 通常给null就行了，给字表赋值时
	 * @param ignore
	 * @return
	 */
	protected void filterParameterMapIgnore(HttpServletRequest request,Object src,Object target,String ...ignore){
		for(String fullkey : request.getParameterMap().keySet()){
			String key = fullkey;
			if(fullkey.indexOf(".")!=-1){
				continue;
			}
			if(ArrayUtils.contains(ignore, key)){
				continue;
			}
			try {
				Object value = PropertyUtils.getProperty(src, key);
				PropertyUtils.setProperty(target, key, value);
			} catch (IllegalAccessException | InvocationTargetException| NoSuchMethodException e) {
//				e.printStackTrace();
			}
		};
	}

	/**
	 * 页面值给后台实体赋值
	 * 
	 * @param request
	 * @param src
	 * @param target
	 * @param prefix 通常给null就行了，给字表赋值时
	 * @param ignore
	 * @return
	 */
	protected void filterParameterMapMore(HttpServletRequest request,Object src,Object target,String ...more){
		Set<String> moreSet=null;
		if(more.length>0){
			moreSet = new TreeSet<String>(Arrays.asList(more));
		}
		for(String fullkey : request.getParameterMap().keySet()){
			String key = fullkey;
			if(fullkey.indexOf(".")!=-1){
				continue;
			}
			if(moreSet!=null){
				moreSet.remove(key);
			}
			try {
				Object value = PropertyUtils.getProperty(src, key);
				PropertyUtils.setProperty(target, key, value);
			} catch (IllegalAccessException | InvocationTargetException| NoSuchMethodException e) {
//				e.printStackTrace();
			}
		};
		for(String key : more){
			try {
				Object value = PropertyUtils.getProperty(src, key);
				PropertyUtils.setProperty(target, key, value);
			} catch (IllegalAccessException | InvocationTargetException| NoSuchMethodException e) {
//				e.printStackTrace();
			}
		}
	}
	
	
}
